package com.taobao.txc.a.b;

import com.taobao.txc.common.LoggerInit;
import com.taobao.txc.common.LoggerWrap;
import com.taobao.txc.common.TxcContext;
import com.taobao.txc.common.c.B;
import com.taobao.txc.common.c.D;
import com.taobao.txc.common.c.E;
import com.taobao.txc.common.util.c.e;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;

@ChannelHandler.Sharable
public class g
  extends p
  implements com.taobao.txc.a.a.b
{
  private static final LoggerWrap t = LoggerInit.logger;
  private static g u;
  private AtomicLong v = new AtomicLong(0L);
  private NioEventLoopGroup w = new NioEventLoopGroup(1);
  private com.taobao.txc.a.a.a x;
  protected ConcurrentHashMap<String, Object> a = new ConcurrentHashMap();
  protected ConcurrentHashMap<String, Channel> b = new ConcurrentHashMap();
  private volatile Map<String, String> y = new ConcurrentHashMap();
  private volatile Map<String, String> z = new ConcurrentHashMap();
  private String A;
  private String B;
  private Set<String> C = null;
  private int D = 0;
  private static Random E = new Random(System.currentTimeMillis());
  private String F;
  private String G;
  private static int H = 0;
  private static boolean I = false;
  public static String c = null;
  private static List<o> J = Collections.synchronizedList(new ArrayList());
  public static Map<Integer, Integer> d = new HashMap();
  public boolean e = false;
  public LinkedList<String> f = new LinkedList();
  public Map<String, String> g = new ConcurrentHashMap();
  private long K = System.currentTimeMillis();
  private static com.taobao.txc.common.util.b.a L = null;
  public static boolean h = false;
  
  protected g(ThreadPoolExecutor paramThreadPoolExecutor)
  {
    super(paramThreadPoolExecutor);
  }
  
  public static g a()
  {
    if (u == null) {
      throw new com.taobao.txc.common.b.c("RpcClient not inited.");
    }
    return u;
  }
  
  public static com.taobao.txc.common.util.b.a c()
  {
    return L;
  }
  
  public static List<o> d()
  {
    return J;
  }
  
  public static g a(ThreadPoolExecutor paramThreadPoolExecutor)
  {
    if (u == null)
    {
      u = new g(paramThreadPoolExecutor);
      com.taobao.txc.common.config.o.a().c(new h());
      com.taobao.txc.common.config.o.a().d(new i());
    }
    return u;
  }
  
  public static void e()
  {
    Collections.sort(J);
    int i = 0;
    Iterator localIterator1 = J.iterator();
    while (localIterator1.hasNext())
    {
      o localo1 = (o)localIterator1.next();
      i += localo1.b;
    }
    if (i <= 0) {
      return;
    }
    int k = 0;
    int m = 0;
    d.clear();
    Iterator localIterator2 = J.iterator();
    while (localIterator2.hasNext())
    {
      o localo2 = (o)localIterator2.next();
      int j = localo2.b * 100 / i;
      for (int n = 0; n < j; n++) {
        d.put(Integer.valueOf(k++), Integer.valueOf(m));
      }
      m++;
    }
    if (k < 100) {
      while (k < 100) {
        d.put(Integer.valueOf(k++), Integer.valueOf(m - 1));
      }
    }
  }
  
  public static String f()
  {
    if (u != null) {
      return u.l();
    }
    return null;
  }
  
  public void b()
  {
    a(5L, 5L);
  }
  
  private void n()
  {
    this.k.a(l(), new j(this));
  }
  
  private void o()
  {
    this.A = q();
    this.e = com.taobao.txc.common.config.o.b(false);
    t.info("RpcClient skip vip " + this.e);
    n();
  }
  
  public void a(long paramLong1, long paramLong2)
  {
    try
    {
      o();
    }
    catch (Exception localException1)
    {
      try
      {
        t.warn("server list get failed on current env");
        throw com.taobao.txc.common.b.c.a(localException1);
      }
      catch (Exception localException2)
      {
        if (!h) {
          throw com.taobao.txc.common.b.c.a(localException2);
        }
      }
    }
    this.m.scheduleAtFixedRate(new k(this), paramLong1, paramLong2, TimeUnit.SECONDS);
    new Thread(new l(this)).start();
    super.b();
  }
  
  private void p()
  {
    Iterator localIterator = this.k.a().iterator();
    while (localIterator.hasNext())
    {
      String str = (String)localIterator.next();
      try
      {
        c(str);
      }
      catch (Exception localException)
      {
        t.error(com.taobao.txc.common.b.b.s.bd, "can not connect to " + str + " cause:" + localException.getMessage());
      }
    }
  }
  
  public void channelInactive(ChannelHandlerContext paramChannelHandlerContext)
  {
    if (this.j.isShutdown()) {
      return;
    }
    t.info("channel inactive:" + paramChannelHandlerContext.channel());
    a(paramChannelHandlerContext.channel(), com.taobao.txc.common.d.a(paramChannelHandlerContext.channel().remoteAddress()));
    super.channelInactive(paramChannelHandlerContext);
  }
  
  public void a(long paramLong, ChannelHandlerContext paramChannelHandlerContext, Object paramObject)
  {
    if (this.x != null)
    {
      Object localObject = com.taobao.txc.common.d.a(paramChannelHandlerContext.channel().remoteAddress());
      String str = (String)this.z.get(localObject);
      if (str != null) {
        localObject = str;
      }
      this.x.a(paramLong, (String)localObject, paramObject);
    }
  }
  
  public Object a(Object paramObject, long paramLong)
  {
    String str1 = null;
    String str2 = com.taobao.txc.common.j.b(TxcContext.getCurrentXid());
    try
    {
      str1 = b(str2);
    }
    catch (Exception localException1)
    {
      t.info("channel is not ok. msg:" + paramObject + ",exception:" + localException1);
      if (((paramObject instanceof com.taobao.txc.common.c.n)) && (TxcContext.b() != null))
      {
        t.info("I will ask next node (" + TxcContext.b() + ") to finish the rollback " + paramObject + ". real node is " + str2);
        str1 = b(TxcContext.b());
        ((com.taobao.txc.common.c.n)paramObject).a(str2);
      }
      else
      {
        if ((localException1 instanceof IOException)) {
          throw ((IOException)localException1);
        }
        if ((localException1 instanceof TimeoutException)) {
          throw ((TimeoutException)localException1);
        }
        throw new com.taobao.txc.common.b.c(localException1);
      }
    }
    Object localObject = super.a(str1, c(str1), paramObject, paramLong);
    if (((localObject instanceof com.taobao.txc.common.c.c)) && (((com.taobao.txc.common.c.c)localObject).a() != B.a.a()))
    {
      Channel localChannel = (Channel)this.b.remove(str1);
      if (localChannel != null) {
        try
        {
          localChannel.disconnect();
          localChannel.close();
          com.taobao.txc.common.g.a(localChannel);
        }
        catch (Exception localException2)
        {
          t.a("", "close channel " + localChannel + " fail.", localException2);
        }
      }
    }
    return localObject;
  }
  
  protected String b(String paramString)
  {
    if (paramString != null) {
      return c(paramString) == null ? null : paramString;
    }
    String str;
    if (c == null)
    {
      str = h().b;
      if (t.c()) {
        t.debug("round robin load balance:" + str);
      }
    }
    else
    {
      str = g().b;
      if (t.c()) {
        t.debug("weight load balance:" + str);
      }
    }
    return str;
  }
  
  public n g()
  {
    if (t.c()) {
      t.debug("weight load banlance");
    }
    int i = 0;
    Integer localInteger = (Integer)d.get(Integer.valueOf(E.nextInt(100)));
    if (localInteger == null) {
      return h();
    }
    i = localInteger.intValue();
    for (int j = 0; j < 2; j++)
    {
      List localList = this.k.a();
      if (localList.size() == 0) {
        throw new com.taobao.txc.common.b.c(B.b.a(), "can not find txc server.");
      }
      if (localList.size() < 3) {
        return h();
      }
      String str = ((o)J.get(i)).c;
      if (localList.contains(str)) {
        return new n(c(str), str);
      }
      synchronized (J)
      {
        ((o)J.get(i)).a(3);
        e();
      }
      int k = 0;
      for (int m = 0; m < 100; m++)
      {
        localInteger = (Integer)d.get(Integer.valueOf(E.nextInt(100)));
        if (localInteger == null) {
          return h();
        }
        if (localInteger.intValue() != i)
        {
          i = k;
          break;
        }
      }
    }
    return h();
  }
  
  public n h()
  {
    if (t.c()) {
      t.debug("round robin load banlance");
    }
    int i = 0;
    for (;;)
    {
      List localList = this.k.a();
      if (localList.size() == 0) {
        throw new com.taobao.txc.common.b.c(B.b.a(), "can not find txc server.");
      }
      int j = (int)(this.v.getAndIncrement() % localList.size());
      String str = (String)localList.get(j);
      i++;
      if (i <= localList.size())
      {
        Channel localChannel = (Channel)this.b.get(str);
        if ((localChannel != null) && (localChannel.isActive()))
        {
          H = 0;
          I = true;
          return new n(localChannel, str);
        }
      }
      else
      {
        try
        {
          t.warn("all channels are not ok.");
          I = false;
          synchronized (this)
          {
            if ((H < 1) && (!I) && (System.currentTimeMillis() - this.K > 180000L))
            {
              if (this.k.a(l(), (String)this.g.get(localList.get(0)), L))
              {
                H += 1;
                Thread.sleep(30000L);
                this.K = System.currentTimeMillis();
                return h();
              }
            }
            else if (I) {
              return h();
            }
          }
        }
        catch (Exception localException)
        {
          t.a(com.taobao.txc.common.b.b.aA, localException);
        }
        return new n(c((String)this.k.a().get(0)), (String)this.k.a().get(0));
      }
    }
  }
  
  public Object a(String paramString, Object paramObject, long paramLong)
  {
    return a(paramString, c(paramString), paramObject, paramLong);
  }
  
  public void channelRead(ChannelHandlerContext paramChannelHandlerContext, Object paramObject)
  {
    if ((paramObject instanceof u))
    {
      u localu = (u)paramObject;
      if (localu.f() == a.b)
      {
        if (t.c()) {
          t.debug("received PONG from " + paramChannelHandlerContext.channel().remoteAddress());
        }
        return;
      }
      if ((((u)paramObject).f() instanceof E))
      {
        E localE = (E)((u)paramObject).f();
        D localD = (D)this.r.remove(Long.valueOf(((u)paramObject).e()));
        int i = localD.a.size();
        for (int j = 0; j < i; j++)
        {
          long l = ((Long)localD.b.get(j)).longValue();
          b localb = (b)this.n.remove(Long.valueOf(l));
          if (localb == null) {
            t.info("msg:" + l + " is not found in futures.");
          } else {
            localb.a(localE.b()[j]);
          }
        }
        return;
      }
    }
    super.channelRead(paramChannelHandlerContext, paramObject);
  }
  
  public void userEventTriggered(ChannelHandlerContext paramChannelHandlerContext, Object paramObject)
  {
    if ((paramObject instanceof IdleStateEvent))
    {
      IdleStateEvent localIdleStateEvent = (IdleStateEvent)paramObject;
      if (localIdleStateEvent.state() == IdleState.READER_IDLE)
      {
        t.info("channel" + paramChannelHandlerContext.channel() + " read idle.");
        try
        {
          paramChannelHandlerContext.disconnect();
          paramChannelHandlerContext.close();
          com.taobao.txc.common.g.a(paramChannelHandlerContext.channel());
        }
        catch (Exception localException) {}
      }
      if (localIdleStateEvent == IdleStateEvent.WRITER_IDLE_STATE_EVENT) {
        try
        {
          a(paramChannelHandlerContext.channel(), a.a);
        }
        catch (Throwable localThrowable)
        {
          t.a("", "send request error", localThrowable);
        }
      }
    }
  }
  
  public void a(Channel paramChannel, String paramString)
  {
    try
    {
      Object localObject1 = this.a.get(paramString);
      if (localObject1 == null)
      {
        this.a.putIfAbsent(paramString, new Object());
        localObject1 = this.a.get(paramString);
      }
      synchronized (localObject1)
      {
        Channel localChannel = (Channel)this.b.get(paramString);
        if ((paramChannel == null) || ((localChannel != null) && (localChannel.compareTo(paramChannel) == 0)))
        {
          if ((paramChannel == null) && ((paramChannel = localChannel) == null)) {
            return;
          }
          this.b.remove(paramString);
          try
          {
            t.info("release channel:" + paramChannel);
            paramChannel.disconnect();
            paramChannel.close();
            com.taobao.txc.common.g.a(paramChannel);
          }
          catch (Exception localException2)
          {
            t.a("", "close channel" + paramChannel + " fail.", localException2);
          }
        }
      }
    }
    catch (Exception localException1)
    {
      localException1 = localException1;
    }
    finally {}
  }
  
  protected Channel c(String paramString)
  {
    Channel localChannel = (Channel)this.b.get(paramString);
    if (localChannel != null)
    {
      if (localChannel.isActive()) {
        return localChannel;
      }
      int i = 0;
      for (i = 0; i < 1000; i++)
      {
        try
        {
          Thread.sleep(10L);
        }
        catch (InterruptedException localInterruptedException) {}
        localChannel = (Channel)this.b.get(paramString);
        if (localChannel == null) {
          break;
        }
        if (localChannel.isActive()) {
          return localChannel;
        }
      }
      if (i == 1000)
      {
        t.warn("channel " + localChannel + " is not active after long wait, close it.");
        a(localChannel, paramString);
      }
    }
    Object localObject1 = this.a.get(paramString);
    if (localObject1 == null)
    {
      this.a.putIfAbsent(paramString, new Object());
      localObject1 = this.a.get(paramString);
    }
    synchronized (localObject1)
    {
      localChannel = e(paramString);
      this.b.put(paramString, localChannel);
      return localChannel;
    }
  }
  
  public String d(String paramString)
  {
    String str = null;
    if ((!this.e) && (this.y != null)) {
      str = (String)this.y.get(paramString);
    }
    return str;
  }
  
  protected Channel e(String paramString)
  {
    Object localObject1 = (Channel)this.b.get(paramString);
    if ((localObject1 != null) && (((Channel)localObject1).isActive())) {
      return localObject1;
    }
    String str1 = d(paramString);
    InetSocketAddress localInetSocketAddress;
    if (str1 != null)
    {
      localInetSocketAddress = com.taobao.txc.common.d.a(str1);
      t.info(String.format("vip: %s ==> %s", new Object[] { paramString, str1 }));
    }
    else
    {
      localInetSocketAddress = com.taobao.txc.common.d.a(paramString);
    }
    t.info("connect to " + paramString);
    Bootstrap localBootstrap = new Bootstrap();
    ((Bootstrap)((Bootstrap)((Bootstrap)((Bootstrap)((Bootstrap)((Bootstrap)localBootstrap.group(this.w)).channel(NioSocketChannel.class)).remoteAddress(localInetSocketAddress).option(ChannelOption.TCP_NODELAY, Boolean.valueOf(true))).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Integer.valueOf(10000))).option(ChannelOption.SO_KEEPALIVE, Boolean.valueOf(true))).option(ChannelOption.SO_REUSEADDR, Boolean.valueOf(true))).handler(new m(this));
    long l = System.currentTimeMillis();
    Object localObject2 = null;
    Channel localChannel = null;
    ChannelFuture localChannelFuture = localBootstrap.connect();
    try
    {
      localChannelFuture.await(15L, TimeUnit.SECONDS);
      if (localChannelFuture.isCancelled()) {
        throw new com.taobao.txc.common.b.c("connect concelled, can not connect to txc server.");
      }
      if (!localChannelFuture.isSuccess()) {
        throw new com.taobao.txc.common.b.c("connect failed, can not connect to txc server.");
      }
      localChannel = localChannelFuture.channel();
    }
    catch (Exception localException1)
    {
      throw new com.taobao.txc.common.b.c(localException1, "can not connect to txc server.");
    }
    try
    {
      String str2 = this.B;
      if (this.A != null) {
        str2 = String.format("%s##%s", new Object[] { str2, com.taobao.txc.common.d.b() });
      }
      c localc = new c(str2, com.taobao.txc.common.util.c.g.a(this.C), l(), this.D);
      String str3 = localc.a(this.F, this.G);
      t.info(String.format("client calc digest with accessKey %s", new Object[] { this.F }));
      localObject2 = super.a(null, localChannel, localc, 3000L);
      if ((localObject2 != null) && ((localObject2 instanceof d)))
      {
        if (((d)localObject2).d())
        {
          localObject1 = localChannel;
        }
        else
        {
          t.info("register client app failed. server version:" + ((d)localObject2).b());
          throw new com.taobao.txc.common.b.c(B.b.a(), "register client app failed.");
        }
      }
      else
      {
        if (localChannel != null) {
          localChannel.close();
        }
        throw new com.taobao.txc.common.b.c(B.b.a(), "can not register app name.");
      }
      L = new com.taobao.txc.common.util.b.a(this.F, str2, str3, l());
    }
    catch (Exception localException2)
    {
      t.a(com.taobao.txc.common.b.b.t.bd, "register client app failed.", localException2);
      if (localChannel != null) {
        localChannel.close();
      }
      throw new com.taobao.txc.common.b.c(B.b.a(), "can not register app.");
    }
    t.info("register client app sucesss. server cost " + (System.currentTimeMillis() - l) + " ms, version:" + ((d)localObject2).b() + ",channel:" + localObject1);
    return localObject1;
  }
  
  public void a(com.taobao.txc.a.a.a parama)
  {
    this.x = parama;
  }
  
  public void a(String paramString)
  {
    this.B = paramString;
  }
  
  public void a(long paramLong, String paramString, Object paramObject)
  {
    super.a(paramLong, c(paramString), paramObject);
  }
  
  public void a(Set<String> paramSet)
  {
    this.C = paramSet;
  }
  
  public void f(String paramString)
  {
    this.F = paramString;
  }
  
  public void g(String paramString)
  {
    this.G = paramString;
  }
  
  public void a(int paramInt)
  {
    this.D = paramInt;
  }
  
  public void exceptionCaught(ChannelHandlerContext paramChannelHandlerContext, Throwable paramThrowable)
  {
    t.a(com.taobao.txc.common.b.b.ad.bd, com.taobao.txc.common.d.a(paramChannelHandlerContext.channel().remoteAddress()) + "connect exception. " + paramThrowable.getMessage(), paramThrowable);
    Iterator localIterator = this.b.entrySet().iterator();
    while (localIterator.hasNext()) {
      if (((Channel)((Map.Entry)localIterator.next()).getValue()).compareTo(paramChannelHandlerContext.channel()) == 0)
      {
        localIterator.remove();
        t.info("remove channel:" + paramChannelHandlerContext.channel());
      }
    }
    super.exceptionCaught(paramChannelHandlerContext, paramThrowable);
  }
  
  private static String q()
  {
    Object localObject1 = null;
    String str1 = "cat /proc/self/cgroup | grep \"cpu:/\" | awk   -F ':' '{print $3}' | sed -e 's#/##g'";
    com.taobao.txc.common.util.a locala = new com.taobao.txc.common.util.a();
    try
    {
      locala.a(str1, com.taobao.txc.common.util.d.b);
      String str2 = locala.a(com.taobao.txc.common.util.d.a, 2000L);
      if ((e.b(str2)) || ((str2.charAt(0) == '/') && (e.b(str2.substring(1))))) {
        localObject1 = str2;
      }
    }
    catch (Throwable localThrowable)
    {
      if (t.c()) {
        t.debug(String.format("getDockerId execute failed:%s", new Object[] { localThrowable }));
      }
    }
    finally
    {
      locala.a();
    }
    return localObject1;
  }
}


/* Location:           C:\Users\ibm\Downloads\txc-yun-sample (1)\txc-yun-sample\lib\txc-client-2.0.72.jar
 * Qualified Name:     com.taobao.txc.a.b.g
 * JD-Core Version:    0.7.0.1
 */